'use client';
import styles from './page.module.css';
import { useState, useRef, useEffect } from 'react';
import { Socket } from 'socket.io-client';
import io from 'socket.io-client';

interface Message {
  id: string;
  text: string;
  userId: string;
  username: string;
  timestamp: string;
}

interface UserInfo {
  id: string;
  username: string;
}

interface MessageItemProps {
  message: Message;
  onEdit: (messageId: string, newText: string, originalQuestion: string) => void;
  findUserQuestion: (messageId: string) => string;
}

export default function Home() {
  const [inputValue, setInputValue] = useState('');
  const [messages, setMessages] = useState<Message[]>([]);
  const [socket, setSocket] = useState<typeof Socket | null>(null);
  const [userInfo, setUserInfo] = useState<UserInfo | null>(null);
  const [isSending, setIsSending] = useState(false);
  const [sessionId, setSessionId] = useState('');
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const [showTransferModal, setShowTransferModal] = useState(false);
  const [transferTarget, setTransferTarget] = useState('');
  const [showRateModal, setShowRateModal] = useState(false);
  const [rateType, setRateType] = useState<'up' | 'down' | null>(null);
  const [rateComment, setRateComment] = useState('');

  // 滚动到底部
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, isSending]);

  // 初始化用户信息
  useEffect(() => {
    const savedUser = sessionStorage.getItem('chatUser');
    if (savedUser) {
      setUserInfo(JSON.parse(savedUser));
    }
  }, []);

  // 初始化Socket连接
  useEffect(() => {
    if (!userInfo) return;

    const newSocket = io("wss://bzmjkyxnliaz.sealoshzh.site", {
      transports: ['websocket'],
      query: { 
        userId: userInfo.id,
        username: userInfo.username
      }
    });
    
    // 消息更新监听
    newSocket.on('messageUpdate', (updatedMsg: Message) => {
      console.log(updatedMsg);
      alert('知识库更新成功');
    });

    // 消息添加监听
    newSocket.on('messageAdd', (msgAdd: Message) => {
      console.log(msgAdd);
      alert('知识库添加成功');
    })

    // 接收普通消息
    newSocket.on('message', (msg: Message) => {
      console.log('收到普通消息:', msg);
      if (msg && typeof msg === 'object') {
        setMessages(prev => {
          // 检查消息是否已存在
          const exists = prev.some(m => m.id === msg.id);
          if (exists) return prev;
          return [...prev, msg];
        });
        setIsSending(false);
      }
      // 如果是用户自己的消息，不要设置 isSending 为 false
      if (msg.userId !== userInfo.id) {
        setIsSending(false);
      }
    });

    // 接收客服消息
    newSocket.on('kefuMessage', (msg: Message) => {
      console.log('收到客服消息:', msg);
      if (msg && typeof msg === 'object') {
        setMessages(prev => {
          // 检查消息是否已存在
          const exists = prev.some(m => m.id === msg.id);
          if (exists) return prev;
          return [...prev, msg];
        });
      }
      setIsSending(false);
    });

    // 接收AI消息
    newSocket.on('aiMessage', (response: Message) => {
      console.log('收到AI消息:', response);
      if (response && typeof response === 'object') {
        setMessages(prev => {
          // 检查消息是否已存在
          const exists = prev.some(m => m.id === response.id);
          if (exists) return prev;
          return [...prev, response];
        });
      }
      // AI消息接收后，设置 isSending 为 false
      setIsSending(false);
    });

    // 错误处理
    newSocket.on('error', (err: Error) => {
      console.error('连接错误:', err);
      setIsSending(false);
    });

    // 接收客服对话消息
    newSocket.on('session', (data: { roomId: string; kefu: string; userId: string }) => {
      console.log('房间号', data.roomId);
      console.log('用户要连接的客服是', data.kefu);
      setSessionId(data.roomId);
      const owner = JSON.parse(sessionStorage.getItem('chatUser') || '{}');
      
      if (owner.username === data.kefu || owner.id === data.userId) {
        // 加入房间
        newSocket.emit('joinRoom', {
          roomId: data.roomId,
          userId: owner.id,
          username: owner.username
        });
      }
    });

    setSocket(newSocket);

    return () => { 
      newSocket.off('messageUpdate');
      newSocket.off('messageAdd');
      newSocket.off('kefuMessage');
      newSocket.off('aiMessage');
      newSocket.off('error');
      newSocket.off('session');
      newSocket.off('joinRoom');
      newSocket.close()
     };
  }, [userInfo]);

  const handleSend = async () => {
    if (!inputValue.trim() || !socket || !userInfo || isSending) return;
    
    try {
      setIsSending(true);
      const messageText = inputValue.trim();
      setInputValue('');
      
      // 检查是否是转人工请求
      const isTransferToHuman = messageText.startsWith('转人工');
      
      // 发送消息到后端
      socket.emit('message', {
        isChange: isTransferToHuman || userInfo.username.startsWith('客'),
        content: messageText,
        userId: userInfo.id,
        username: userInfo.username,
        roomId: isTransferToHuman ? undefined : sessionId, // 转人工请求不需要 roomId
      }, (response: { status: string; message?: string; roomId?: string }) => {
        if (response.status === 'success') {
          if (response.roomId) {
            // 如果是转人工成功，保存返回的roomId
            setSessionId(response.roomId);
          }
        } else {
          console.error('发送失败:', response.message);
          alert(response.message || '发送失败');
          setIsSending(false);
        }
      });

    } catch (err) {
      console.error('发送失败:', err);
      setIsSending(false);
    }
  };
 
  const handleRate = () => {
    // 评价逻辑
    setShowRateModal(true);
  };

  const handleRateSubmit = () => {
    // 你的提交逻辑
    socket?.emit('evaluate', {
      chatId: JSON.parse(sessionStorage.getItem('chatUser') || '{}').id,
      text: rateComment
    })
    setShowRateModal(false);
    setRateType(null);
    setRateComment('');
    socket?.on('evaluate', (response: string) => {
      alert(response)
    })
  };
  
  const handleEditMessage = (messageId: string, newText: string, originalQuestion: string) => {
    if (!socket || !userInfo) return;
    // 发送完整编辑数据
    socket.emit('editMessage', {
      messageId,
      originalQuestion,
      modifiedAnswer: newText,
      editor: {
        id: userInfo.id,
        name: userInfo.username
      },
      timestamp: new Date().toISOString()
    });
  };
  
  const findUserQuestion = (messageId: string) => {
    const index = messages.findIndex(msg => msg.id === messageId);
    if (index === -1) return '';
    for (let i = index - 1; i >= 0; i--) {
      if (messages[i].userId === userInfo?.id) {
        return messages[i].text;
      }
    }
    return '';
  };

  // 消息项组件（添加加载状态）
  const MessageItem = ({ message, onEdit, findUserQuestion }: MessageItemProps) => {
    const [isEditing, setIsEditing] = useState(false);
    const [editedText, setEditedText] = useState(message.text);
    const isCurrentUser = message.userId === userInfo?.id;
    const isSystem = message.userId === 'AI';
    const isPending = message.id === 'temp';

    const timeString = new Date(message.timestamp).toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    });

    return (
      <div className={`${styles.message} 
        ${isCurrentUser ? styles.right : styles.left}
        ${isPending ? styles.pending : ''}`}
      >
        {!isCurrentUser && (
          <div className={styles.avatar}>
            {isSystem ? '🤖' : message.username?.charAt(0).toUpperCase()}
          </div>
        )}
        <div className={styles.messageContent}>
          <div className={styles.messageHeader}>
            <span className={styles.username}>
              {isCurrentUser ? '朕' : message.username}
            </span>
            <span className={styles.time}>{timeString}</span>
          </div>
          
          <div className={styles.messageText}>
            {message.text}
            {isPending && <span className={styles.loadingDot} />}
          </div>
        </div>
        {isCurrentUser && (
          <div className={styles.avatar}>
            {message.username.charAt(0).toUpperCase()}
          </div>
        )}
        {isSystem && (
          <button 
            className={styles.editButton}
            onClick={() => setIsEditing(true)}
          >
            ✎
          </button>
        )}
        {isEditing && (
          <div className={styles.editModal}>
            <div className={styles.editForm}>
              <h3>修改回复内容</h3>
              <div className={styles.formGroup}>
                <label>用户问题</label>
                <input 
                  type="text" 
                  value={findUserQuestion(message.id) || '未知问题'}
                  readOnly
                />
              </div>
              <div className={styles.formGroup}>
                <label>机器人回复</label>
                <textarea
                  value={editedText}
                  onChange={(e) => setEditedText(e.target.value)}
                  rows={4}
                />
              </div>
              <div className={styles.formActions}>
                <button onClick={() => {
                  const originalQuestion = findUserQuestion(message.id);
                  if (!originalQuestion) return;
                  onEdit(message.id, editedText, originalQuestion);
                  setIsEditing(false);
                }}>
                  添加/修改
                </button>
                <button onClick={() => setIsEditing(false)}>取消</button>
              </div>
            </div>
          </div>
        )}
      </div>
    );
  };

  const handleLogin = (username: string) => {
    const newId = crypto.randomUUID?.() || `user_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
    const userData: UserInfo = { id: newId, username };
    sessionStorage.setItem('chatUser', JSON.stringify(userData));
    localStorage.setItem(`user_${username}`, JSON.stringify(userData));
    setUserInfo(userData);
  };

  const handleTransfer = () => {
    setShowTransferModal(true);
  };

  const handleTransferSubmit = () => {
    if (!transferTarget.trim()) {
      alert('请输入目标客服名称');
      return;
    }

    if (!socket || !sessionId) {
      alert('连接异常，请刷新页面重试');
      return;
    }

    socket.emit('message', {
      isChange: true,
      content: `转人工${transferTarget}`,
      userId: userInfo?.id,
      username: userInfo?.username,
      roomId: sessionId
    }, (response: { status: string; message?: string }) => {
      if (response.status === 'success') {
        setShowTransferModal(false);
        setTransferTarget('');
      } else {
        alert(response.message || '转接失败，请重试');
      }
    });
  };

  return (
    <main className={styles.container}>
      {!userInfo ? (
        <LoginForm onLogin={handleLogin} />
      ) : (
        <div className={styles.chatRoom}>
          <div className={styles['chatRoom-header']}>
            <h2>电脑商铺--{userInfo.username}</h2>
          </div>
          <div className={styles['chatRoom-content']}>
            {messages.map((message, index) => (
              <MessageItem key={message.id || index} message={message} onEdit={handleEditMessage} findUserQuestion={findUserQuestion} />
            ))}
            <div ref={messagesEndRef} />
          </div>
          <div className={styles.buttonGroup}>
            {JSON.parse(sessionStorage.getItem('chatUser') || '{}')?.username?.startsWith('客') ? (
              <button
                className={`${styles.actionButton} ${styles.humanButton}`}
                onClick={() => handleTransfer()} // 转接客服的新处理函数
              >
                转接给其他客服
              </button>
            ) : (
            <><button
                className={`${styles.actionButton} ${styles.rateButton}`}
                onClick={() => handleRate()}
              >
                评价
              </button></>
            )}
          </div>
          <div className={styles['chatRoom-footer']}>
            <input
              type="text"
              className={styles.input}
              placeholder="请输入消息..."
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && handleSend()}
              disabled={isSending}
            />
            <button 
              className={styles.sendButton}
              onClick={handleSend}
              disabled={!inputValue.trim() || isSending}
            >
              {isSending ? (
                <div className={styles.spinner}>
                  <div className={styles.bounce1} />
                  <div className={styles.bounce2} />
                  <div className={styles.bounce3} />
                </div>
              ) : '发送'}
            </button>
          </div>
          {showTransferModal && (
            <div className={styles.modalOverlay}>
              <div className={styles.modal}>
                <h3>转接客服</h3>
                <input
                  type="text"
                  value={transferTarget}
                  onChange={(e) => setTransferTarget(e.target.value)}
                  placeholder="请输入目标客服名称"
                  className={styles.modalInput}
                />
                <div className={styles.modalButtons}>
                  <button 
                    onClick={handleTransferSubmit}
                    className={styles.modalSubmit}
                  >
                    确认
                  </button>
                  <button 
                    onClick={() => {
                      setShowTransferModal(false);
                      setTransferTarget('');
                    }}
                    className={styles.modalCancel}
                  >
                    取消
                  </button>
                </div>
              </div>
            </div>
          )}
          {showRateModal && (
            <div className={styles.rateModalOverlay}>
              <div className={styles.rateModalContent}>
                <div className={styles.rateModalTitle}>请评价这条回复</div>
                
                <div className={styles.rateButtonGroup}>
                  <div 
                    className={`${styles.rateOption} ${rateType === 'up' ? styles.active : ''}`}
                    onClick={() => setRateType('up')}
                  >
                    <span className={styles.rateIcon}>👍</span>
                    <span className={styles.rateText}>赞</span>
                  </div>
                  
                  <div 
                    className={`${styles.rateOption} ${rateType === 'down' ? styles.active : ''}`}
                    onClick={() => setRateType('down')}
                  >
                    <span className={styles.rateIcon}>👎</span>
                    <span className={styles.rateText}>踩</span>
                  </div>
                </div>

                <textarea
                  className={styles.rateInput}
                  placeholder="请输入评价内容（选填）"
                  value={rateComment}
                  onChange={(e) => setRateComment(e.target.value)}
                />

                <div className={styles.rateModalActions}>
                  <button 
                    className={styles.rateCancelButton}
                    onClick={() => setShowRateModal(false)}
                  >
                    取消
                  </button>
                  <button 
                    className={styles.rateSubmitButton}
                    disabled={!rateType}
                    onClick={() => handleRateSubmit()}
                  >
                    提交
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      )}
    </main>
  );
}

const LoginForm = ({ onLogin }: { onLogin: (username: string) => void }) => {
  const [input, setInput] = useState('');

  return (
    <div className={styles.loginOverlay}>
      <div className={styles.loginBox}>
        <h3>欢迎咨询店铺</h3>
        <input
          type="text"
          placeholder="请输入用户名（1-12个字符）"
          value={input}
          onChange={(e) => setInput(e.target.value.slice(0, 12))}
          autoFocus
        />
        <button 
          onClick={() => input.trim() && onLogin(input.trim())}
          disabled={!input.trim()}
        >
          进入聊天
        </button>
      </div>
    </div>
  );
}